package cn.itrip.auth.controller;

import cn.itrip.auth.service.LoginService;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.dto.Dto;
import cn.itrip.utlis.DtoUtil;
import cn.itrip.utlis.RedisAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisAPI redisAPI;
    @RequestMapping(value = "/dologin",method = RequestMethod.POST)
    public Dto login(String name, String password, HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        ItripUser user = loginService.login(name, password);
        if(user != null) {
            if(user.getActivated()==0){
                return DtoUtil.returnFail("用户尚未激活","30002");
            }
         return DtoUtil.returnSuccess("登录成功", loginService.createToken(user,userAgent));
        }
        return DtoUtil.returnFail("用户名或密码错误","30002");
    }

    @GetMapping("/logout")
    public Dto logout() {
        redisAPI.del("token");
        return DtoUtil.returnSuccess();
    }

}
